//
//  MIDIrecommendedController.m
//  迷笛
//
//  Created by . on 2018/9/15.
//  Copyright © 2018年 🍃🌺🌺🍃. All rights reserved.
//

#import "MIDIrecommendedController.h"
#import "MIDIreommCell.h"
#import "MIDIYuedongtwoController.h"
#import "MIDIlandingController.h"
#import "MIDIcirclemodel.h"
@interface MIDIrecommendedController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, copy) NSString *categoryId;
@property(nonatomic,strong)UITableView * recommtable;
@property(nonatomic,copy)NSString * apptoken;
@property(nonatomic,copy)NSString * recommendedApi;
@property(nonatomic,copy)NSString * praiseapi;
@property(nonatomic,copy)NSString * outapi;

@property(nonatomic,copy)NSNumber *join;
@property(nonatomic,copy)NSMutableArray * circleArr;
@end

@implementation MIDIrecommendedController

-(instancetype)initWithCategoryId:(NSString*)categoryId
{
    if (self = [super init]) {
        self.categoryId = categoryId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    _apptoken = [user objectForKey:@"APPToken"];
    

    [self recommendedRequest];
    _circleArr = [NSMutableArray array];
    
    self.view.backgroundColor =[UIColor colorWithHexString:@"#171717"];
    [self HomeUI];
    
    
}

//-(void)viewWillAppear:(BOOL)animated
//{
//    [self recommendedRequest];
//    _circleArr = [NSMutableArray array];
//}


-(void)outcircle:(NSInteger)indexRow
{
    NSNumber * typeNumber = [self.circleArr[indexRow] modelId];
    
    
    _outapi = [NSString stringWithFormat:@"%@circle/out/%@?token=%@",MIDIApiRoot,typeNumber,_apptoken];
    
    NSLog(@"praiseRequest--%@",_outapi);
    
    [EdHttp get:_outapi params:nil progress:^(id downloadProgress)
     {
         
     }
        success:^(id responseObject)
     {
         NSLog(@"退出圈子%@",responseObject);
         if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
         {
             MIDIcirclemodel *model = self.circleArr[indexRow];
             model.isjoin = @0;
             [SVProgressHUD showSuccessWithStatus:@"退出圈子成功"];
             [SVProgressHUD dismissWithDelay:1.0];
             
             NSLog(@"退出成功");
         }
         else
         {
             NSLog(@"失败");
         }
     }
        failure:^(NSError *error)
     {
         NSLog(@"失败");
     }];
}

-(void)HomeUI
{
    [self.view addSubview:self.recommtable];
    
}
-(UITableView *)recommtable
{
    if (!_recommtable)
    {
        _recommtable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kDevice_Is_iPhoneX?HeighX(600):HeightScale(520)) style:UITableViewStyleGrouped];
        _recommtable.dataSource = self;
        _recommtable.delegate = self;
        _recommtable.backgroundColor = [UIColor colorWithHexString:@"#1B212F"];
    }
    return _recommtable;
}
//加入按钮
-(void)fousbtn:(UIButton *)sender
{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    _apptoken = [user objectForKey:@"APPToken"];
    
    if (self.apptoken == nil)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"notification_modal_login" object:nil];
        //
        return;
    }
    else
    {
        
        CGPoint point = sender.center;
        point = [self.recommtable convertPoint:point fromView:sender.superview];
        NSIndexPath* indexpath = [self.recommtable indexPathForRowAtPoint:point];
        NSLog(@"第%ld行Cell",(long)indexpath.row);
        
        
        if (sender.selected == YES)
        {
            NSNumber *typeNumber = [self.circleArr[sender.tag] modelId];
            //
            _praiseapi = [NSString stringWithFormat:@"%@circle/join/%@?token=%@",MIDIApiRoot,typeNumber,_apptoken];
            //
            NSLog(@"praiseRequest--%@",_praiseapi);
            //
            [EdHttp get:_praiseapi params:nil progress:^(id downloadProgress)
             {
                 
             }
                success:^(id responseObject)
             {
                 sender.selected=!sender.selected;//每次点击都改变按钮的状态
                 NSLog(@"加入成功%@",responseObject);
                 if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
                 {
                     
                     MIDIreommCell *selCell = [self.recommtable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0]];
                     MIDIcirclemodel *selModel = self.circleArr[sender.tag];
                     NSString *origenAttentionNum = selModel.join;
                     selModel.join = [NSString stringWithFormat:@"%ld",[origenAttentionNum integerValue] + 1];
                     selCell.recommendFocus.text = [NSString stringWithFormat:@"%@%@",@"关注",selModel.join];
                     
                     //第一次点击为蓝色（关注）
                     MIDIcirclemodel *model = self.circleArr[sender.tag];
                     model.isjoin = @1;
                     [sender setBackgroundColor:[UIColor colorWithHexString:@"#999999"]];
                     [sender setTitle:@"已加入" forState:UIControlStateNormal];
                     [sender setAccessibilityFrame:CGRectMake(0, 0, WidthScale(100), HeightScale(40))];
                     
                     [SVProgressHUD showSuccessWithStatus:@"加入圈子成功"];
                     [SVProgressHUD dismissWithDelay:1.0];
                     NSLog(@"已关注");
                 }
                 else
                 {
                     NSLog(@"加入失败");
                 }
             }
                failure:^(NSError *error)
             {
                 NSLog(@"失败");
             }];
        }
        
        else
        {
            UIAlertController *controller=[UIAlertController alertControllerWithTitle:@"确认不再加入此圈？" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *act1=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [act1 setValue:[UIColor colorWithHexString:@"#171717"] forKey:@"titleTextColor"];
            
            UIAlertAction *act2=[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
        {
            sender.selected=!sender.selected;//每次点击都改变按钮的状态
            MIDIreommCell *selCell = [self.recommtable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:0]];
            MIDIcirclemodel *selModel = self.circleArr[sender.tag];
            NSString *origenAttentionNum = selModel.join;
            selModel.join = [NSString stringWithFormat:@"%ld",[origenAttentionNum integerValue] - 1];
            selCell.recommendFocus.text = [NSString stringWithFormat:@"%@%@",@"关注",selModel.join];
                                     
            [self outcircle:sender.tag];
            [sender setBackgroundColor:[UIColor colorWithHexString:@"#FF005D"]];
        
            [sender setTitle:@"加入" forState:UIControlStateNormal];
            NSLog(@"取消关注");
        }];
            
            [act2 setValue:[UIColor colorWithHexString:@"#FF005D"] forKey:@"titleTextColor"];
            [controller addAction:act1];
            [controller addAction:act2];
            [self presentViewController:controller animated:YES completion:^{
            }];
            
        }
    }
}

-(void)recommendedRequest
{
    NSString * ID = self.categoryId;
    NSString * page = @"1";
    
    self.recommendedApi = [NSString stringWithFormat:@"%@circle/%@?page=%@&token=%@",MIDIApiRoot,ID,page,_apptoken];
    
//    NSLog(@"_recommendedtoken---%@",self.recommendedApi);
    [EdHttp get:self.recommendedApi params:nil progress:^(id downloadProgress)
     {
         
     }
        success:^(id responseObject)
     {
         NSLog(@"圈子推荐%@",responseObject);
         NSArray *arr4 = responseObject[@"data"];
         for (NSDictionary *dic4 in arr4)
         {
             NSString * circlename;
             NSString * circleiamge;
             NSString * join_peopel;
             NSString * post_people;
             NSNumber * is_join;
             NSString * intro;
             if (![dic4[@"name"] isKindOfClass:[NSNull class]]){
                 circlename = dic4[@"name"];
             }
             else{
                 circlename = @"";
             }
             if (![dic4[@"cover"] isKindOfClass:[NSNull class]]){
                 circleiamge = dic4[@"cover"];
             }
             else{
                 circleiamge = @"";
             }
             if (![dic4[@"join_peopel"] isKindOfClass:[NSNull class]]){
                 join_peopel = dic4[@"join_peopel"];
             }
             else{
                 join_peopel = @"";
             }
             if (![dic4[@"post_people"] isKindOfClass:[NSNull class]]){
                 post_people = dic4[@"post_people"];
             }
             else{
                 post_people = @"";
             }
             if (![dic4[@"is_join"] isKindOfClass:[NSNull class]]){
                 is_join = dic4[@"is_join"];
             }
             else{
             }
             if (![dic4[@"intro"] isKindOfClass:[NSNull class]]){
                 intro = dic4[@"intro"];
             }
             else{
                 intro = @"";
             }
             
             MIDIcirclemodel * mmact = [MIDIcirclemodel new];
             mmact.modelId = dic4[@"id"];
             mmact.name = circlename;
             mmact.cover =circleiamge;
             mmact.join = join_peopel;
             mmact.post = post_people;
             mmact.isjoin = is_join;
             mmact.intro = intro;
             [self.circleArr addObject:mmact];
             
         }
         dispatch_async(dispatch_get_main_queue(), ^{
             [self.recommtable reloadData];
             
         });
     }
        failure:^(NSError *error)
     {
         
     }];
}

#pragma mark -- delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return _circleArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString * cellID = @"cell";
    MIDIreommCell * cell =[tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell =[[MIDIreommCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [_recommtable setSeparatorColor : [UIColor blackColor]];
    }
    MIDIcirclemodel *mm1 = _circleArr[indexPath.row];
    [cell.headimage sd_setImageWithURL:[NSURL URLWithString:mm1.cover] placeholderImage:nil];
    cell.recommendName.text =mm1.name;
    cell.recommendFocus.text = [NSString stringWithFormat:@"关注%@",mm1.join];
    cell.recommendTZ.text = [NSString stringWithFormat:@"帖子数%@",mm1.post];
    
    if ([[_circleArr[indexPath.row] isjoin] isEqualToNumber:@1])
    {
        [cell.recommendFocusBtn setBackgroundColor:[UIColor colorWithHexString:@"#999999"]];
        [cell.recommendFocusBtn setTitle:@"已加入" forState:UIControlStateNormal];
        [cell.recommendFocusBtn addTarget:self action:@selector(fousbtn:) forControlEvents:UIControlEventTouchUpInside];
        cell.recommendFocusBtn.selected = NO;
        cell.recommendFocusBtn.tag = indexPath.row;

    }
    else
    {
        [cell.recommendFocusBtn setTitle:@"加入" forState:UIControlStateNormal];
        [cell.recommendFocusBtn setBackgroundColor:[UIColor colorWithHexString:@"#FF005D"]];
        cell.recommendFocusBtn.tag = indexPath.row;
        [cell.recommendFocusBtn addTarget:self action:@selector(fousbtn:) forControlEvents:UIControlEventTouchUpInside];
        cell.recommendFocusBtn.selected = YES;

    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kDevice_Is_iPhoneX?HeighX(74):HeightScale(74);
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
- ( UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
{
    return nil;
}
- ( UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
{
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    _apptoken = [user objectForKey:@"APPToken"];
    if (self.apptoken == nil)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"notification_modal_login" object:nil];
        
        return;
    }
    else
    {
        
        MIDIYuedongtwoController * yuedong =[[MIDIYuedongtwoController alloc]init];
        MIDIcirclemodel * circlemodel = _circleArr[indexPath.row];
        yuedong.ID = circlemodel.modelId;
        yuedong.name = circlemodel.name;
        yuedong.fans = circlemodel.join;
        yuedong.TZ = circlemodel.post;
        yuedong.intro = circlemodel.intro;
        yuedong.cover = circlemodel.cover;
        [self.navigationController pushViewController:yuedong animated:YES];
    }
}



@end
